package com.tudouji.project.repository.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.tudouji.common.exception.CustomException;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.project.permission.service.ISalespermissionService;
import com.tudouji.project.store.domain.Storeroom;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.tudouji.framework.aspectj.lang.annotation.Log;
import com.tudouji.framework.aspectj.lang.enums.BusinessType;
import com.tudouji.project.repository.domain.RptStoreanalysis;
import com.tudouji.project.repository.service.IRptStoreanalysisService;
import com.tudouji.framework.web.controller.BaseController;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.common.utils.poi.ExcelUtil;
import com.tudouji.framework.web.page.TableDataInfo;

/**
 * 动态库存Controller
 *
 * @author tudouji
 * @date 2021-05-13
 */
@RestController
@RequestMapping("/repository/storeanalysis")
public class RptStoreanalysisController extends BaseController {
    @Autowired
    private IRptStoreanalysisService rptStoreanalysisService;
    @Autowired
    private ISalespermissionService permissionService;

    /**
     * 查询动态库存列表
     */
    @GetMapping("/listReport")
    public TableDataInfo listReport(@RequestParam(value = "starttime", required = false) String starttime, @RequestParam(value = "endtime", required = false) String endtime,
                                    @RequestParam(value = "srguid", required = false) String srguid, @RequestParam(value = "orgguidcondition", required = false) String orgguidcondition,
                                    @RequestParam(value = "othercondition", required = false) String othercondition, @RequestParam(value = "byday", required = false) String byday,
                                    RptStoreanalysis rptStoreanalysis) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<Storeroom> rm;
        if (StringUtils.isBlank(srguid)) {
            String userid = SecurityUtils.getLoginUser().getUser().getTuserId();
            if (StringUtils.isNotBlank(userid)) {
                rm = permissionService.getPermssionForSr(userid, "10");
                if (null == rm) {
                    throw new CustomException("无授权库房！");
                } else {
                    if (rm.size() > 0) {
                        String[] rmids = new String[rm.size()];
                        for (int i = 0; i < rm.size(); i++) {
                            if (rptStoreanalysis.getSrtype() == rm.get(i).getType()) {
                                if (StringUtils.isNotEmpty(rptStoreanalysis.getFarmerid())) {
                                    if (rptStoreanalysis.getFarmerid().equalsIgnoreCase(rm.get(i).getFarmerid())) {
                                        rmids[i] = rm.get(i).getGuid();
                                    }
                                } else {
                                    rmids[i] = rm.get(i).getGuid();
                                }
                            }

                        }
                        rptStoreanalysis.setSrids(rmids);
                    }

                }
            } else {
                throw new CustomException("未授权！");
            }
        } else {
            String[] srgs = srguid.split(",");
            rptStoreanalysis.setSrids(srgs);
        }

        if (StringUtils.isNotBlank(rptStoreanalysis.getCompanyid())) {
            String[] companyids = rptStoreanalysis.getCompanyid().split(",");
            rptStoreanalysis.setCompanyid(null);
            rptStoreanalysis.setCompanyids(companyids);
        }
        try {
            if (StringUtils.isNotBlank(starttime)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(df.parse(starttime));
                calendar.add(Calendar.DATE, -1);
                rptStoreanalysis.setStartdate(calendar.getTime());
                rptStoreanalysis.setStarttime(df.parse(starttime));
            } else {
                Date date = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, -2);
                rptStoreanalysis.setStartdate(calendar.getTime());
                rptStoreanalysis.setStarttime(date);
            }
            if (StringUtils.isNotBlank(endtime)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(df.parse(endtime));
                calendar.add(Calendar.DATE, -1);
                rptStoreanalysis.setEnddate(calendar.getTime());
                rptStoreanalysis.setEndtime(df.parse(endtime));
            } else {
                Date date = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, -1);
                rptStoreanalysis.setEnddate(calendar.getTime());
                rptStoreanalysis.setEndtime(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        rptStoreanalysis.setOrgguidcondition(orgguidcondition);
        rptStoreanalysis.setOthercondition(othercondition);
        startPage();
        List<RptStoreanalysis> rpts = rptStoreanalysisService.findRPT(rptStoreanalysis);
        return getDataTable(rpts);

    }

    /**
     * 查询动态库存列表
     */
    @PreAuthorize("@ss.hasPermi('repository:storeanalysis:list')")
    @GetMapping("/list")
    public TableDataInfo list(RptStoreanalysis rptStoreanalysis) {
        startPage();
        List<RptStoreanalysis> list = rptStoreanalysisService.selectRptStoreanalysisList(rptStoreanalysis);
        return getDataTable(list);
    }

    /**
     * 导出动态库存列表
     */
    @PreAuthorize("@ss.hasPermi('repository:storeanalysis:export')")
    @Log(title = "动态库存", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(@RequestParam(value = "starttime", required = false) String starttime, @RequestParam(value = "endtime", required = false) String endtime,
                             @RequestParam(value = "srguid", required = false) String srguid, @RequestParam(value = "orgguidcondition", required = false) String orgguidcondition,
                             @RequestParam(value = "othercondition", required = false) String othercondition, @RequestParam(value = "byday", required = false) String byday,
                             RptStoreanalysis rptStoreanalysis) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject result = new JSONObject();
        try {
            List<Storeroom> rm = new ArrayList<>();
            if (StringUtils.isBlank(srguid)) {
                String userid = SecurityUtils.getLoginUser().getUser().getTuserId();
                if (StringUtils.isNotBlank(userid)) {
                    rm = permissionService.getPermssionForSr(userid, "10");
                    if (null == rm) {
                        return AjaxResult.error("无授权库房！");
                    } else {
                        if (rm.size() > 0) {
                            String[] rmids = new String[rm.size()];
                            for (int i = 0; i < rm.size(); i++) {
                                if (rptStoreanalysis.getSrtype() == rm.get(i).getType()) {
                                    if (StringUtils.isNotEmpty(rptStoreanalysis.getFarmerid())) {
                                        if (rptStoreanalysis.getFarmerid().equalsIgnoreCase(rm.get(i).getFarmerid())) {
                                            rmids[i] = rm.get(i).getGuid();
                                        }
                                    } else {
                                        rmids[i] = rm.get(i).getGuid();
                                    }
                                }

                            }
                            rptStoreanalysis.setSrids(rmids);
                        }

                    }
                } else {
                    return AjaxResult.error("登录异常");
                }
            } else {
                String[] srgs = srguid.split(",");
                rptStoreanalysis.setSrids(srgs);
            }

            if (StringUtils.isNotBlank(rptStoreanalysis.getCompanyid())) {
                String[] companyids = rptStoreanalysis.getCompanyid().split(",");
                rptStoreanalysis.setCompanyid(null);
                rptStoreanalysis.setCompanyids(companyids);
            }

            if (StringUtils.isNotBlank(starttime)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(df.parse(starttime));
                calendar.add(Calendar.DATE, -1);
                rptStoreanalysis.setStartdate(calendar.getTime());
                rptStoreanalysis.setStarttime(df.parse(starttime));
            } else {
                Date date = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, -2);
                rptStoreanalysis.setStartdate(calendar.getTime());
                rptStoreanalysis.setStarttime(date);
            }
            if (StringUtils.isNotBlank(endtime)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(df.parse(endtime));
                calendar.add(Calendar.DATE, -1);
                rptStoreanalysis.setEnddate(calendar.getTime());
                rptStoreanalysis.setEndtime(df.parse(endtime));
            } else {
                Date date = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, -1);
                rptStoreanalysis.setEnddate(calendar.getTime());
                rptStoreanalysis.setEndtime(date);
            }
//            rptStoreanalysis.setSrguid(srguid);
            rptStoreanalysis.setOrgguidcondition(orgguidcondition);
            rptStoreanalysis.setOthercondition(othercondition);
            List<RptStoreanalysis> rpts = null;
            if (rptStoreanalysis.getSrids().length > 0 && StringUtils.isBlank(byday)) {
                rpts = rptStoreanalysisService.findRPT(rptStoreanalysis);
                RptStoreanalysis rptsSum = rptStoreanalysisService.findRPTSUM(rptStoreanalysis);
                result.put("data", rpts);
                result.put("datasum", rptsSum);
                result.put("result", "success");
            } else if (rptStoreanalysis.getSrids().length > 0 && StringUtils.isNotBlank(byday)) {
                rptStoreanalysis.setByday(byday);
                rpts = rptStoreanalysisService.findRPTByDay(rptStoreanalysis);
                RptStoreanalysis rptsSum = rptStoreanalysisService.findRPTByDaySUM(rptStoreanalysis);
                result.put("data", rpts);
                result.put("datasum", rptsSum);
                result.put("result", "success");
            }
            ExcelUtil<RptStoreanalysis> util = new ExcelUtil<RptStoreanalysis>(RptStoreanalysis.class);
            return util.exportExcel(rpts, "storeanalysis");
        } catch (Exception ex) {
            ex.printStackTrace();
            return AjaxResult.error("系统异常");
        }
    }

    /**
     * 获取动态库存详细信息
     */
    @PreAuthorize("@ss.hasPermi('repository:storeanalysis:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid) {
        return AjaxResult.success(rptStoreanalysisService.selectRptStoreanalysisById(guid));
    }

    /**
     * 新增动态库存
     */
    @PreAuthorize("@ss.hasPermi('repository:storeanalysis:add')")
    @Log(title = "动态库存", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RptStoreanalysis rptStoreanalysis) {
        return toAjax(rptStoreanalysisService.insertRptStoreanalysis(rptStoreanalysis));
    }

    /**
     * 修改动态库存
     */
    @PreAuthorize("@ss.hasPermi('repository:storeanalysis:edit')")
    @Log(title = "动态库存", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RptStoreanalysis rptStoreanalysis) {
        return toAjax(rptStoreanalysisService.updateRptStoreanalysis(rptStoreanalysis));
    }

    /**
     * 删除动态库存
     */
    @PreAuthorize("@ss.hasPermi('repository:storeanalysis:remove')")
    @Log(title = "动态库存", businessType = BusinessType.DELETE)
    @DeleteMapping("/{guids}")
    public AjaxResult remove(@PathVariable String[] guids) {
        return toAjax(rptStoreanalysisService.deleteRptStoreanalysisByIds(guids));
    }
}
